package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private  SetMealDao setMealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        addSetMeal(setmeal);
        Integer setmealId = setmeal.getId();
        addSetMealAndCheckGroup(setmealId,checkgroupIds);
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
//      将动态mobile的页面通过freeMarker转换为静态mobile页面
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
//        获取静态页面所需要的map数据
        List<Setmeal> setmeals = setMealDao.findAll();
//        生成一个setmeal.html对应的静态页面
        generateMobileSetmealListHtml(setmeals);
//        生成多个setmeal_detail对应的静态页面
        generateMobileSetmealDetailHtml(setmeals);
    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> setmeals) {
        for (Setmeal setmeal : setmeals) {
            Map<String ,Object> map  =new HashMap();
            map.put("setmeal", setMealDao.findById(setmeal.getId()));
            generateStaticHtml("mobile_setmeal_detail.ftl", "setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    private void generateMobileSetmealListHtml(List<Setmeal> setmeals) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("setmealList",setmeals);
        generateStaticHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //  通用的生成一个静态页面的方法
    private void generateStaticHtml(String inputFTLName,String outputHTMLName,Map dataMap)  {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(inputFTLName);
            outPutPath = new String(outPutPath.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println(outPutPath);
            writer=new FileWriter(outPutPath+"/"+outputHTMLName);
            template.process(dataMap, writer);
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }finally {
            if (writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            
        }
    }

    private  void addSetMeal(Setmeal setmeal){
        setMealDao.addSetMeal(setmeal);
    }
    private   void addSetMealAndCheckGroup(Integer setmealId,Integer[] checkgroupsId){
        Map<String ,Integer> setMealAndCheckGroupMap = new HashMap<>();
        for (Integer checkgroupId : checkgroupsId) {
            setMealAndCheckGroupMap.put("setmeal_id", setmealId);
            setMealAndCheckGroupMap.put("checkgroup_id", checkgroupId);
            setMealDao.addSetMealAndCheckGroup(setMealAndCheckGroupMap);
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Setmeal findSetmealById(Integer id) {
        Setmeal setmeal = setMealDao.findSetmealById(id);
        return setmeal;
    }

    @Override
    public List<Integer> findCheckgroupBySetmealId(Integer id) {
        List<Integer> checkGroupIds =setMealDao.findCheckgroupBySetmealId(id);
        return checkGroupIds;
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkGroupIds) {
        //            设置 套餐的基本信息
        setMealDao.setSetmeal(setmeal);
//        删除关联表中对应的套餐的所有信息
        setMealDao.deleteSetmealAndGroup(setmeal.getId());
//        将新的对应关系添加到关联表中
        this.addSetMealAndCheckGroup(setmeal.getId(),checkGroupIds);
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
    }

    @Override
    public void deleteSetmealById(Integer id) {
        //        删除关联表中对应的套餐的所有信息
        setMealDao.deleteSetmealAndGroup(id);
//        删除检查组中的数据
        setMealDao.deleteSetmeal(id);
    }
//查询所有的套餐信息
    @Override
    public List<Setmeal> findAllSetmeal() {

        return  setMealDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {

        return setMealDao.findById(id);
    }
}
